package com.sunky.rfidapp.util

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import java.io.IOException
import java.io.PrintWriter
import java.io.StringWriter

class CommonUtil{
    companion object {
        val GlobalStorage = hashMapOf<String,Any>()

        fun logToString(e : Throwable):String{
            var stringWriter : StringWriter? = null
            var printWriter : PrintWriter? = null
            try {
                stringWriter = StringWriter()
                printWriter = PrintWriter(stringWriter)
                e.printStackTrace(printWriter)
                printWriter.flush()
                stringWriter.flush()
            }finally {
                try {
                    stringWriter?.close()
                }catch (e : IOException){
                    e.printStackTrace()
                }
                try {
                    printWriter?.close()
                }catch (e : IOException){
                    e.printStackTrace()
                }

                return stringWriter?.toString()?:"Unknown error"
            }
        }
    }
}

fun TextView.setTextValid(str : String?){
    if (str != null && str?.isNotEmpty()){
        this.text = str
    }else{
        (parent as ViewGroup).visibility = View.GONE
    }
}

fun Context.showException(ex:Throwable){
//    var traceElements = ex.getStackTrace()
//
//    var traceBuilder =  StringBuilder()
//    traceBuilder.append(ex.message).append('\n')
//    if (traceElements != null && traceElements.isNotEmpty()) {
//        traceElements.forEach {
//            traceBuilder.append(it.toString())
//            traceBuilder.append("\n")
//        }


        showInfoDialog(CommonUtil.logToString(ex))
}